#include <iostream>
#include <fstream>

#include "aktazo.h"
#include "menu.h"

///aktazo.cpp is class implementation for aktazo.h

Aktazo::Aktazo():filename("adatok.dat"),v_ptr(new std::vector<Document>)
{
	try
	{
		load_data();
		run();
		save_data();
	}
	catch(Exceptions e)
	{
		switch(e)
		{
			case FILE_READ_ERROR:
			{
				std::cerr<<"Hiba: a(z) '"<<filename<<"' fajlt nem lehetett olvasasra megnyitni."<<std::endl;
				break;
			}
			case FILE_WRITE_ERROR:
			{
				std::cerr<<"Hiba: a(z) '"<<filename<<"' fajlt nem lehetett irasra megnyitni."<<std::endl;
				break;
			}
			default:
			{
				std::cerr<<"Hiba: kezeletlen kivetel itt: Aktazo::."<<std::endl;
				break;
			}
		}
	}
}

Aktazo::~Aktazo()
{
	///closing files if they are still open
	if(f_out.is_open())
	{
		f_out.close();
	}
	if(f_in.is_open())
	{
		f_in.close();
	}
}

void Aktazo::load_data()
{
	std::clog<<"Adatfajl beolvasasa: ";
	f_in.open(filename.c_str());
	if(f_in.fail())
	{
		throw FILE_READ_ERROR;
	}
	int i=0;
	///counter for read records
	int k=1;
	///divisor for counter: 1, 10, 100 etc.
	while(!f_in.eof())
	{
		Document d;
		f_in>>d;
		v_ptr->push_back(d);
		++i;
		if(i==10*k)
		{
			///prints a '+' sign when reading
			///the 10th, 100th, 1000th etc. record
			std::clog<<'+';
			k=10*k;
		}
		else if(0 ==i%k)
		{
			///prints a '.' sign when reading the
			///1,2..9th, 20,30..90th, 200,300..900th record
			std::clog<<'.';
		}
	}
	f_in.close();
	v_old_size=v_ptr->size();
	///number of read recors
	std::clog<<" "<<v_old_size<<" rekord beolvasva."<<std::endl;
}

void Aktazo::run()
{
	Menu menu(v_ptr);
}

void Aktazo::save_data()
{
	v_new_size=v_ptr->size();
	///number of all stored recors
	if(v_new_size!=v_old_size)
	{
		///at least one new record to save
		std::cout<<"Mentes."<<std::endl;
		std::clog<<"Uj rekordok rogzitese ";
		f_out.open(filename.c_str(),std::ios::app);
		if(f_out.fail())
		{
			throw FILE_WRITE_ERROR;
		}
		int ii=0;
		///counter for written records
		int k=1;
		///divisor for counter: 1, 10, 100 etc.
		for(unsigned int i=v_old_size;i<v_new_size;++i)
		{
			ii=i-v_old_size;
			if(0!=i)
			{
				f_out<<std::endl;
			}
			f_out<<v_ptr->at(i);
			++ii;
			if(ii==10*k)
			{
				///prints a '+' sign when writing the
				///10th, 100th, 1000th etc. record
				std::clog<<'+';
				k=10*k;
			}
			else if(0 ==ii%k)
			{
				///prints a '.' sign when writing the
				///1,2..9th, 20,30..90th, 200,300..900th record
				std::clog<<'.';
			}
		}
		f_out.close();
		std::clog<<" "<<v_new_size-v_old_size<<" uj rekrord rogzitve, "<<v_new_size<<" osszesen."<<std::endl;
	}
	std::cout<<"Kilepes."<<std::endl;
}
